import { Component, Input, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Consts } from 'src/app/consts/consts';
import { MenuQueryParam } from 'src/app/models/param/menu-query.param';
import { MenuDto } from 'src/app/models/sys/menu.dto';
import { ApiService } from 'src/app/services/api.service';
import { AppSettingsService } from 'src/app/services/app-settings.service';
import { LoginInfoService } from 'src/app/services/login-info.service';

@Component({
  selector: 'app-nav',
  templateUrl: './nav.component.html',
  styleUrls: ['./nav.component.less']
})
export class NavComponent implements OnInit {
  @Input() isLoggedIn!: boolean;

  menus: MenuDto[] = [];
  
  constructor(private _loginInfoService: LoginInfoService, 
    private _api: ApiService, private _router: Router,
    private _appSettings: AppSettingsService) {
      const settings = _appSettings.getSettings();
    }

  ngOnInit(): void {
    console.log('Nav init');
    const param = new MenuQueryParam();
    param.withButton = false;
    this._api.getMenuTree(param).subscribe((resp) => {
      if (resp.code == Consts.RESP_OK && resp.data) {
        console.log(`Nav get menu OK with ${resp.data.length} items`);
        this.buildTreeLevel(resp.data);
        this.menus = resp.data;
      }
    });
  }

  buildTreeLevel(param: MenuDto[]) {
    if (param == null || param.length == 0) {
      return;
    }

    for (const parent of param) {
      this.buildMenuLevel(parent, 0);
    }
  }

  buildMenuLevel(menu: MenuDto, level: number) {
    menu.level = level;
    // console.log(`set ${menu.menuName} to ${level}`);

    if (menu.children) {
      for (const child of menu.children) {
        this.buildMenuLevel(child, level + 1);
      }
    }
  }

  clickMenu(menu: MenuDto) {
    console.log(`menu checked ${menu.menuName}:${menu.path}`);

    if (menu != null && menu.menuType == 'M') {
      console.log(`navigate to ${menu.path}`);
      this._router.navigateByUrl(menu.path!);
    }
  }
}
